<template>
  <div id="globalSider">
    <a-layout-sider
      v-if="loginUserStore.loginUser.id"
      class="sider"
      :width="200"
      :collapsed-width="80"
      :trigger="null"
      collapsible
      v-model:collapsed="collapsed"
      @mouseover="collapsed = false"
      @mouseleave="collapsed = true"
    >
      <a-menu
        mode="inline"
        v-model:selectedKeys="current"
        :items="menuItems"
        @click="doMenuClick"
      />
    </a-layout-sider>
  </div>
</template>
<script lang="ts" setup>
import { computed, h, ref, watchEffect } from 'vue'
import { PictureOutlined, UserOutlined, TeamOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { useLoginUserStore } from '@/stores/useUserLoginStore.ts'
import { SPACE_TYPE_ENUM } from '@/constants/space.ts'
import { listMyTeamSpaceUsingPost } from '@/api/spaceUserController.ts'
import { message } from 'ant-design-vue'

const loginUserStore = useLoginUserStore()
const collapsed = ref(true)

// 菜单列表
const teamSpaceList = ref<API.SpaceUserVO[]>([])

const menuItems = computed(() => {
  // 构建团队空间子菜单
  const teamSpaceSubMenus = teamSpaceList.value.map((spaceUser) => {
    const space = spaceUser.space
    if (space===null){
      return
    }
    return {
      key: '/space/' + spaceUser.spaceId,
      label: space?.spaceName,
    }
  })
  teamSpaceSubMenus.push({
    key: '/addSpace?type=' + SPACE_TYPE_ENUM.TEAM,
    label: '创建团队空间',
  })
  // 构建团队空间菜单项（替换原先的固定路径）
  const teamSpaceMenu = {
    key: '/addSpace',
    label: '团队空间',
    icon: () => h(TeamOutlined),
    children: teamSpaceSubMenus,
  }

  const fixedMenuItems = [
    {
      key: '/',
      label: '公共图库',
      icon: () => h(PictureOutlined),
    },
    {
      key: '/mySpace',
      label: '我的空间',
      icon: () => h(UserOutlined),
    },
  ]

  // 没有团队空间，不展示团队空间菜单项
  if (teamSpaceSubMenus.length < 1) {
    return fixedMenuItems
  }
  return [...fixedMenuItems, teamSpaceMenu]
})

// 加载团队空间列表
const fetchTeamSpaceList = async () => {
  const res = await listMyTeamSpaceUsingPost()
  if (res.data.code === 0 && res.data.data) {
    teamSpaceList.value = res.data.data
  } else {
    message.error('加载我的团队空间失败，' + res.data.message)
  }
}

/**
 * 监听变量，改变时触发数据的重新加载
 */
watchEffect(() => {
  // 登录才加载
  if (loginUserStore.loginUser.id) {
    fetchTeamSpaceList()
  }
})

const router = useRouter()
// 当前高亮菜单项
const current = ref<string[]>([])
// 监听路由变化，更新菜单高亮
router.afterEach((to, from, failure) => {
  current.value = [to.path]
})
// 路由跳转事件
const doMenuClick = ({ key }: { key: string }) => {
  router.push(key)
}
</script>
<style scoped>
#globalSider .sider {
  transition: all 0.2s;
}

#globalHeader .title-bar {
  display: flex;
  align-items: center;
}

.logo {
  height: 45px;
}

.title {
  margin-left: 10px;
  color: black;
  font-size: 18px;
}
</style>
